package org.liveboardgames.common.utils.collections
{
    import org.liveboardgames.agricola.vo.player.Player;
    
    import mx.collections.ArrayCollection;
    import mx.collections.ICollectionView;
    import mx.collections.ListCollectionView;
    import mx.collections.Sort;
    
    public class SortUtils
    {
        
        public static function doRandomSort(tempCollection:ICollectionView):void
        {
            
            function randomCompare(a:Object, b:Object, fields:Array = null):int
            {
                var rand:Number = Math.random();
                var result:int;
                if (rand < 0.5)
                {
                    result = 1;
                }
                if (rand > 0.5)
                {
                    result = -1;
                }
                return result;
                ;
            }
            
            var sort:Sort = new Sort();
            sort.compareFunction = randomCompare;
            tempCollection.sort = sort;
            tempCollection.refresh();
        }
        
        public static function circularPermutation(players:ListCollectionView, firstPlayer:Player):void
        {
            var tempArray:ListCollectionView = new ArrayCollection();
            var firstPlayerIndex:int = players.getItemIndex(firstPlayer);
            // Create a temporary array that has the proper final order
            for (var i:int = 0; i < players.length; i++)
            {
                var newIndex:int = (i + firstPlayerIndex) % players.length;
                tempArray.addItem(players.getItemAt(newIndex) as Player);
            }
            
            // Update the initial array
            for (var j:int = 0; j < tempArray.length; j++)
            {
                players.setItemAt(tempArray.getItemAt(j) as Player, j);
            }
        }
    }
}